package com.jdbc.service;


import com.jdbc.entity.TUser;
import com.jdbc.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserDetailService {

    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public TUser getUser(String username){
        TUser tUser =tUserMapper.findByUserName(username);
        System.out.println("数据库查询 getUser");
        return tUser;
    }

    public TUser getUser1(String username){
        TUser tUser = null;
        if (redisTemplate.opsForValue().get("tUser") != null) {
            System.out.println("没有数据库查询 getUser1");
            tUser = (TUser) redisTemplate.opsForValue().get("tUser");
        }
        if (tUser==null){
            System.out.println("数据库查询 getUser1");
            tUser  =tUserMapper.findByUserName(username);
            redisTemplate.opsForValue().setIfAbsent("tUser" , tUser , 20, TimeUnit.SECONDS );
        }
        return tUser;
    }



    /*public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        TUser tUser =  tUserMapper.findByUserName(username);

        System.out.println(passwordEncoder.encode(tUser.getPassword()));
        List<String> permissions = new ArrayList<>();
        if (tUser!=null){
            List<TPermission> tPermissionList =  tUserMapper.findPermissionByUserId(tUser.getId());
            if (!tPermissionList.isEmpty()){
                tPermissionList.forEach(tp->permissions.add( tp.getCode() ) );
            }
        }
        String[] perimArry = new String[permissions.size()];
        permissions.toArray(perimArry);

        UserDetails userDetails = User.withUsername(tUser.getUsername() ).password(tUser.getPassword()).authorities(perimArry).build();

        return userDetails;
    }*/
}
